package edu.bit.water.controller;

import edu.bit.water.entity.MetaCleanProductSub2;
import edu.bit.water.service.MetaCleanProductSub2Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/meta_clean_product_sub2")
public class MetaCleanProductSub2Controller {

    @Autowired
    private MetaCleanProductSub2Service metaCleanProductSub2Service;

    // 查询记录
    @RequestMapping("/select")
    @ResponseBody
    public Map<String, Object> select(int lastId) {
        Map<String, Object> map = new HashMap<>();
        List<MetaCleanProductSub2> list = metaCleanProductSub2Service.select(lastId);

        /*
         * 获取元数据中出现的所有不同的indicator
         * */
        String[] indicator = new String[100];
        int num = 0;
        boolean flag = false;
        for (int i = 0; i < list.size(); i++) {
            flag = false;
            for (int j = 0; j < num; j++) {
                if (list.get(i).getIndicator().equals(indicator[j])) {
                    flag = true;
                    break;
                }
            }
            if (flag == false) {
                indicator[num++] = list.get(i).getIndicator();
            }
        }

        /*
         * 根据indicator出现的顺序，重新排列数据
         * */
        List<MetaCleanProductSub2> sortList = new ArrayList<MetaCleanProductSub2>();
        for (int i = 0; i < num; i++) {
            for (int j = 0; j < list.size(); j++) {
                if (list.get(j).getIndicator().equals(indicator[i])) {
                    sortList.add(list.get(j));
                }
            }
        }

        map.put("status", "success");
        map.put("rows", sortList);
        return map;
    }

    // 新增记录
    @RequestMapping("/insert")
    @ResponseBody
    public Map<String, Object> insert(MetaCleanProductSub2 metaCleanProductSub2) {
        return metaCleanProductSub2Service.insert(metaCleanProductSub2);
    }

    // 编辑记录
    @RequestMapping("/update")
    @ResponseBody
    public Map<String, Object> update(MetaCleanProductSub2 metaCleanProductSub2) {
        return metaCleanProductSub2Service.update(metaCleanProductSub2);
    }

    // 删除记录
    @RequestMapping("/delete")
    @ResponseBody
    public Map<String, Object> delete(@RequestBody List<Integer> ids) {
        Map<String, Object> map = new HashMap<>();
        int n = metaCleanProductSub2Service.delete(ids);
        if (n == 1) {
            map.put("status", "success");
        } else {
            map.put("status", "failed");
        }
        return map;
    }
}
